// pages/participate/participate.js
var app = getApp();
const http = require('../../utils/http.js');
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js'); // 引入腾讯地图SDK核心类
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgArr: [],
    textaraeText: '',
    publicTetxt: '公开',
    itemList: ['公开', '仅我关注的人可见', '私密'],
    address: '',
    latitude: '',
    longitude: '',
    hotHuati: '',
    isClick:false
  },

  addImg() {
    wx.chooseImage({
      count: 9,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        console.log(res.tempFilePaths, this.data.imgArr)
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths

        this.data.imgArr = [...this.data.imgArr, ...tempFilePaths];
        //超过9张截取九张
        if (this.data.imgArr.length>9){
          this.data.imgArr = this.data.imgArr.slice(0,9)
        }
        this.setData({
          imgArr: this.data.imgArr
        })
        console.log(this.data.imgArr)

      }
    })
  },

  //图片上传
  imgUpload() {
    var httpImgs = []
    var imgArr = this.data.imgArr;
    var uploads = [];
    return new Promise((resolve1, reject1) => {
      imgArr.forEach((item, index) => {
        uploads[index] = new Promise((resolve, reject) => {
          wx.showLoading({
            title: '图片上传中',
          })
          wx.uploadFile({
            url: `${app.globalData.host}file`, //仅为示例，非真实的接口地址
            filePath: item,
            name: 'file',
            success: (ret) => {
              
              const data = JSON.parse(ret.data);
              if(data.code==1){
                resolve(data.url)
              }else if(data.code==0){
                wx.showToast({
                  title: data.results,
                  icon:'none'
                })
              }
            
              //百度ai审核图片
            //  http.fetchApi('procedure_t', { p: `R2020008` }).then(result => {
               // if (result.data.code == 1) {
                 // var access_token = result.data.results[0].token;
                  // wx.request({
                  //   url: 'https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined',
                  //   method: 'post',
                  //   header: {
                  //     'content-type': 'application/x-www-form-urlencoded'
                  //   },
                  //   data: {
                  //     access_token,
                  //     imgUrl: data.url
                  //   },
                  //   success:resmsg=>{
                  //     if (resmsg.data.conclusionType==1){
                  //       resolve(data.url)
                  //     }else{
                  //       wx.showToast({
                  //         title: '含有违规图片!',
                  //         icon:'none'
                  //       })
                  //       return
                  //     }
                  //   }
                  // })
               // }
             // })

             
            }
          })
        })

      })
      console.log(uploads)
      Promise.all(uploads).then((httpImgs) => {
        wx.hideLoading();
       // console.log(httpImgs)
        resolve1(httpImgs)
      })

    })


  },

  handleInput(e) {
    var textaraeText = e.detail.value
    var pattern = new RegExp("[|]");
    if (pattern.test(textaraeText)) {
      wx.showToast({
        title: '含有特殊字符|',
        icon: 'none'
      })
    }
    textaraeText = textaraeText.replace(pattern, '*')
    this.setData({
      textaraeText
    })
  },
  //删除照片
  deleteImg(e) {
    wx.showModal({
      title: '提示',
      content: '是否删除当前图片',
      success: (res) => {
        if (res.confirm) {
          var imgId = e.currentTarget.dataset.id;
          this.data.imgArr.splice(imgId, 1);
          this.setData({
            imgArr: this.data.imgArr
          })
        }
      }
    })

  },

  //图片预览
  previewImage(e) {
    var src = e.currentTarget.dataset.src;
    wx.previewImage({
      current: src, // 当前显示图片的http链接
      urls: this.data.imgArr // 需要预览的图片http链接列表
    })
  },

  //选择权限
  authority() {
    var itemList = this.data.itemList
    wx.showActionSheet({
      itemList,
      itemColor: '#1478F6',
      success: (res) => {
        console.log(res.tapIndex);
        var publicTetxt = itemList[res.tapIndex]
        this.setData({
          publicTetxt
        })
      },
      fail(res) {
        console.log(res.errMsg)
      }
    })
  },
  //添加话题
  addTopic() {
    wx.navigateTo({
      url: "/pages/addTopic/addTopic?page=fabudongtai",
    })
  },

  publicType() {
    var itemList = this.data.itemList;
    var publicTetxt = this.data.publicTetxt;
    return publicTetxt == '公开' ? 3 : publicTetxt == '仅我关注的人可见' ? 2 : publicTetxt == '私密' ? 1 : '';
  },

  //打开微信内置地图
  openMap() {
    wx.chooseLocation({
      success: res => {
        console.log(res)
        this.setData({
          latitude: res.latitude,
          longitude: res.longitude,
          address:  res.name
        })
      },
      fail() {
        // wx.showToast({
        //   title: '失败',
        //   icon:''
        // })
      }
    })
  },

  //获取当前位置信息
  getNowLocation() {
    wx.getLocation({
      type: 'wgs84',
      success: (res1) => {
        var latitude = res1.latitude
        var longitude = res1.longitude
        wx.request({
          url: 'https://apis.map.qq.com/ws/geocoder/v1/',
          data: {
            location: `${latitude},${longitude}`,
            key: '4RPBZ-BQILD-DIR4K-HVJ4J-OZJES-GTF5Z'  //申请的key值
          },
          header: {
            'Content-Type': 'application/json'
          },
          success: (res) => {
            // success
            var address = res.data.result.address_component.street_number;

            console.log(res)
            this.setData({
              address,
              latitude,
              longitude
            })

          },
          fail: () => {
            // this.setData({
            //   currentCity: "获取定位失败"
            // });
            wx.showToast({
              title: '定位失败',
              icon: 'none'
            })
          },


        })

      }
    })
  },
  //发布动态
  release() {
    if (!this.data.isclick){
      var pages = getCurrentPages();
      var prePage = pages[pages.length - 2];//上一个页面实例对象
      var topic_id = wx.getStorageSync('hotTopic').id || 0;
      console.log(topic_id)
      var uid = app.globalData.uid;
      var pubType = this.publicType();
      var address = this.data.address;
      var textaraeText = this.data.textaraeText;
      var latitude = this.data.latitude;
      var longitude = this.data.longitude;
      this.imgUpload().then(httpImgs => {
        var httpImgs = httpImgs;

        // httpImgs = httpImgs.join(',')
        console.log(httpImgs)

        //检测敏感词
      //  http.fetchApi('procedure_t', { p: `R2020008` }).then(result => {
         // if (result.data.code == 1) {
          //  var access_token = result.data.results[0].token;
          //  wx.request({
            //  url: 'https://aip.baidubce.com/rest/2.0/antispam/v2/spam',
            //  method: 'post',
             // header: {
             //   'content-type': 'application/x-www-form-urlencoded'
            //  },
            //  data: {
              //  access_token,
               // content: textaraeText
            //  },
             // success: ret => {
               // if (ret.data.result.spam == 0) {
                  http.fetchApi('p_fatie', { p: `R2017009|${topic_id}|${uid}|${pubType}|${address}|${textaraeText}|${httpImgs}|${longitude}|${latitude}` })
                    .then(res => {
                      if (res.data.code == 1) {
                        var pid = res.data.results[0].id;
                        wx.showToast({ title: '发布成功' });
                        if (prePage.route == 'pages/topicDetail/topicDetail') {
                          //如果是参与话题 就跳转话题
                          prePage.getDetails();
                          prePage.getHotDynamic(1)
                          setTimeout(() => {
                            // wx.navigateBack({

                            // })
                            wx.navigateTo({
                              url: '/pages/dynamicDetail/dynamicDetail?pid=' + pid,
                            })
                          }, 1000)
                        } else if (prePage.route == 'pages/community/community') {
                          setTimeout(() => {
                            // wx.reLaunch({
                            //   url: '/pages/community/community',
                            wx.navigateTo({
                              url: '/pages/dynamicDetail/dynamicDetail?pid=' + pid,
                            })
                            // })
                          }, 1000)
                        }

                        this.setData({
                          imgArr: [],
                          textaraeText: ''
                        })
                        wx.removeStorageSync('nowEdit')
                        wx.removeStorageSync('hotTopic')
                      } else {
                        wx.showToast({
                          title: res.data.results,
                          icon: 'none'
                        })
                      }
                    })

                // } else if (ret.data.result.spam == 1) {
                //   wx.showToast({ title: '包含违禁内容!', icon: 'none' });
                //   return
                // } else if (ret.data.result.spam == 2) {
                //   wx.showToast({ title: '违禁内容!建议人工复审', icon: 'none' });
                //   return
                // }
             // }
            //})
         // }
       // })


      });
    }else{
      wx.showToast({
        title: '请勿重复提交',
        icon: 'none'
      })
    }

    //防止多次点击
    this.setData({
      isclick: true
    })
    

  },

  //取消话题
  cancelTopic(){
    this.setData({
      hotHuati:''
    })
    wx.removeStorageSync('hotTopic');
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      userInfo: app.globalData.userInfo
    })
    this.getNowLocation()
    if (wx.getStorageSync('nowEdit')) {
      var { imgArr, textaraeText, publicTetxt } = wx.getStorageSync('nowEdit');
      this.setData({
        imgArr,
        textaraeText,
        publicTetxt
      })
    }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var uid = app.globalData.uid
    http.fetchApi('procedure_t', { p: `R2019002|${uid}|${uid}` }).then(res => {
      if (res.data.code == 1) {
        var infor = res.data.results[0];
        if (infor.school == '未知' || infor.entrance == '未填写' || infor.faculty === '未填写'){
          wx.showModal({
            content: '发布动态前亲可以先完善一下资料让更多同校同学知道你满腹才华哦!',
            confirmText: '马上去',
            confirmColor: '#02BB00',
            success(res) {
              if (res.confirm) {
                wx.navigateTo({
                  url: '/pages/editProfile/editProfile',
                })
              } else if (res.cancel) {

              }
            }
          })
        }
        // this.setData({
        //   infor,
        //   school: infor.school,
        //   year: infor.entrance,
        //   major: infor.faculty,
        //   gxqm: infor.gxqm,
        //   zoidx,
        //   sexidx
        // })
      } else {
        // wx.showToast({
        //   title: '服务器异常',
        //   icon: 'none'
        // })
      }
    })

   
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var hotHuati = wx.getStorageSync('hotTopic');
    this.setData({
      hotHuati
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var textaraeText = this.data.textaraeText;
    var imgArr = this.data.imgArr;
    var publicTetxt = this.data.publicTetxt;
    console.log(textaraeText, imgArr)
    if (textaraeText == '' && imgArr.length == 0) {
      console.log(2222)
      return
    }
    console.log(2222)
    wx.showModal({
      title: '提示',
      confirmColor: '#02BB00;',
      content: '是否保留此次编辑?',
      success: (res) => {
        if (res.confirm) {

          var nowEdit = {
            textaraeText,
            imgArr,
            publicTetxt
          }
          wx.setStorageSync('nowEdit', nowEdit)

        } else if (res.cancel) {
          wx.removeStorageSync('nowEdit');
          wx.removeStorageSync('hotTopic')
        }
      }
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})